#ifndef __PROTOCOLMSG_HPP__
#define __PROTOCOLMSG_HPP__

#include <iostream>
#include <string.h>
#include <nlohmann/json.hpp>
#include <vector>

using namespace std;
using json =  nlohmann::json;

class ProtocolMsg
{
public:
    ProtocolMsg(string s)
    {
        char *msg = (char*)s.c_str();
        /* cout << "ProtocolMsg: todo" << endl; */
        const char *delim = " ";
	    
        //用key存储分割好的字符串
        //第一个元素为id，第二个元素为msglen
        //剩下的元素为key
        vector<string> key;
        char *p;
        p = strtok(msg, delim);
	    while(p) 
        {
		    /* cout << p << endl; */
            string s = p;
            if(p != "\n")
            {
                key.push_back(p);
            }
		    p = strtok(NULL, delim);
        
        }

        /* for(auto &elem : key) */
        /* { */
        /*     cout << elem << endl; */
        /* } */

        //取出第一个元素，赋值给_msgId
        auto it = key.begin();
        /* cout << stoi(*it) << endl; */
        setMsgId(stoi(*it));
        
        //取出第二个元素，赋值给_msgLength
        /* ++it; */
        /* setMsgLength(stoi(*it)); */

        //将剩余的元素赋给_msgContent
        ++it;
        json jsonKey;
        for(int idx = 1; it != key.end(); ++it, ++idx)
        {
            string s = "key" + to_string(idx);
            jsonKey[s] = *it;
        }
        setMsgContent(jsonKey);
        //消息长度为消息内容加id长度和
        _msgLength = sizeof(jsonKey) + 8;
    }

    ProtocolMsg(json msgContent)
    :_msgContent(msgContent)
    {

    }

    ProtocolMsg()
    {

    }

    ~ProtocolMsg()
    {

    }

    void setMsgId(int msgid)
    {
        _msgId = msgid;
    }

    void setMsgLength(int msgLength)
    {
        _msgLength = msgLength;
    }

    void setMsgContent(json msgContent)
    {
        _msgContent = msgContent;
    }

    int getMsgId() const
    {
        return _msgId;
    }

    int getMsgLength() const
    {
        return _msgLength;
    }

    json getMsgContent() const
    {
        return _msgContent;
    }

private:
    int _msgId;
    int _msgLength;
    json _msgContent;
};


#endif
